#include "QtGraphicsStateItem.h"
#include "QtGraphicsLinkItem.h"
#include "QtAnimGraphicsItem.h"
#include <QtGui/QGraphicsSceneMouseEvent>
#include <QtCore/QLineF>
#include <QtGui/QGraphicsScene>

QtGraphicsStateItem::QtGraphicsStateItem(QGraphicsItem* parent/* = 0*/):
	QGraphicsPixmapItem(parent)
{
	setFlag(QGraphicsItem::ItemIsMovable);
	setFlag(QGraphicsItem::ItemIsSelectable);
	setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
	
	setPixmap(QPixmap(":/QtAnimEditor/Icons/State.png"));
}

QtGraphicsStateItem::~QtGraphicsStateItem(void)
{
}

void QtGraphicsStateItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
	if (event->modifiers() == Qt::ControlModifier)
	{
		return;
	}

	setPos(scenePos() + event->scenePos() - event->lastScenePos());
}

void QtGraphicsStateItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
	if (event->modifiers() == Qt::ControlModifier)
	{
		QtGraphicsStateItem* pOtherItem = (QtGraphicsStateItem*)scene()->itemAt(event->scenePos());
		if (pOtherItem && pOtherItem != this)
		{
			QtGraphicsLinkItem* linkItem = new QtGraphicsLinkItem;
			scene()->addItem(linkItem);
			linkItem->setLinks(this, pOtherItem);
			connect(this, SIGNAL(posChanged()), linkItem, SLOT(pathChanged()));
			connect(pOtherItem, SIGNAL(posChanged()), linkItem, SLOT(pathChanged()));
		}
	}
	QGraphicsPixmapItem::mouseMoveEvent(event);
}

QVariant QtGraphicsStateItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
 	{
 		if(change == QGraphicsItem::ItemPositionHasChanged)
 		{
 			emit posChanged();
 			return value;
 		}
 	}

	return QGraphicsPixmapItem::itemChange(change, value);
}

QDataStream & operator << (QDataStream &dataStream, QtGraphicsStateItem &itemBase)
{
	itemBase.save(dataStream);
	return dataStream;
}

QDataStream & operator >> (QDataStream &dataStream, QtGraphicsStateItem &itemBase)
{
	itemBase.load(dataStream);
	return dataStream;
}

void QtGraphicsStateItem::save(QDataStream &dataStream)
{
	dataStream << QString(metaObject()->className());
	dataStream << mStateTrans._translate
		<< mStateTrans._rotate
		<< mStateTrans._scale
		<< pos();
}

void QtGraphicsStateItem::load(QDataStream &dataStream)
{
	QPointF pos;
	dataStream >> mStateTrans._translate
		>> mStateTrans._rotate
		>> mStateTrans._scale
		>> pos;
	setPos(pos);
}